import 'dart:async';

import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:squat_easy/se_coin_shop/se_coin_shop_bean.dart';
import 'package:squat_easy/se_net/se_global_url.dart';
import 'package:squat_easy/se_net/se_net.dart';
import 'package:squat_easy/se_service/se_iap_service.dart';
import 'package:squat_easy/se_service/se_log_service.dart';
import 'package:squat_easy/se_service/se_user_service.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class SeApiCoinShop extends SeApi {
  SeApiCoinShop.goodsList()
      : super(SeGlobalUrl.goodsList, params: {'isIncludeSubscription': false, 'payChannel': 'IAP'});

  SeApiCoinShop.createOrder({required String goodsId})
      : super(SeGlobalUrl.createRechargeOrder, params: {
          'goodsCode': goodsId,
          'payChannel': 'IAP',
          'source': '',
          'entry': '',
        });

  SeApiCoinShop.queryOrder({
    required String orderNo,
    required String payload,
    required String transactionId,
  }) : super(
          SeGlobalUrl.checkRechargeOrder,
          params: {
            'orderNo': orderNo,
            'payload': payload,
            'transactionId': transactionId,
          },
        );
}

class SeCoinShopLogic extends GetxController {
  List<SeGoodsBean> goodsList = [];

  late StreamSubscription<List<PurchaseDetails>> _subscription;

  SePayOrderBean? payOrderBean;

  @override
  void onClose() {
    _subscription.cancel();
    super.onClose();
  }

  @override
  void onReady() async {
    super.onReady();

    final Stream<List<PurchaseDetails>> purchaseUpdated = InAppPurchase.instance.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
    });

    _fetchData();
  }

  ///创建订单
  Future createOrder(SeGoodsBean goodsBean) async {
    if (goodsBean.goodsId.empty) return;
    Loading.show(clickMaskDismiss: false);
    dynamic json = await SeApiCoinShop.createOrder(goodsId: goodsBean.code ?? '').post().catchError((e) {
      Loading.dismiss();
    });
    payOrderBean = SePayOrderBean.fromJson(json);

    ///订单号不存在
    if (Loading.predicate(() => payOrderBean?.orderNo.empty ?? true, 'OrderNo empty', closeLoading: true)) {
      return;
    }

    ///商品id不存在
    String goodsCode = goodsBean.code.getAuto(payOrderBean?.goodsCode ?? '');
    if (Loading.predicate(() => goodsCode.empty, 'GoodsCode empty', closeLoading: true)) return;

    ///发起支付
    try {
      await SeIapService().applePay(
        productId: goodsBean.code ?? '',
        orderNum: payOrderBean!.orderNo!,
      );
    } catch (e) {
      Loading.dismiss();
    }

    SeLogManager.stat(page: SeLogPage.createOrder);
  }

  ///查询订单
  Future queryOrder(String orderNo, String payload, String transactionId) async {
    if (Loading.predicate(
      () => orderNo.empty || payload.empty || transactionId.empty,
      'Param empty',
      closeLoading: true,
    )) {
      return;
    }
    Loading.show(clickMaskDismiss: false);
    await SeApiCoinShop.queryOrder(
      orderNo: orderNo,
      payload: payload,
      transactionId: transactionId,
    ).post().then((value) async {
      await SeUserService.instance.getCacheMineInfoBean(true);
      Loading.toast('Purchase success', closeLoading: true);
    }).catchError((e) {
      Loading.toast('Purchase error', closeLoading: true);
    });
  }

  Future _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) async {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        /// 等待购买中
        // Loading.show(clickMaskDismiss: false);
      } else if (purchaseDetails.status == PurchaseStatus.canceled) {
        /// 取消订单
        SeIapService().completePurchase(purchaseDetails);
        Loading.toast('Purchase cancel', closeLoading: true);
      } else if (purchaseDetails.status == PurchaseStatus.error) {
        /// 购买出错
        Loading.toast('Purchase error', closeLoading: true);
        SeIapService().completePurchase(purchaseDetails);
      } else if (purchaseDetails.status == PurchaseStatus.purchased ||
          purchaseDetails.status == PurchaseStatus.restored) {
        ///购买成功
        SeIapService().completePurchase(purchaseDetails);

        // await Future.delayed(const Duration(milliseconds: 500));

        /// 调用后台接口,发放商品
        queryOrder(
          payOrderBean?.orderNo ?? '',
          purchaseDetails.verificationData.serverVerificationData,
          purchaseDetails.purchaseID ?? '',
        );
      }
    }
  }

  Future _fetchData() async {
    Loading.show(clickMaskDismiss: false);
    dynamic json = await SeApiCoinShop.goodsList().post();
    goodsList = await CommonJson.getList(json, (json) => SeGoodsBean.fromJson(json));
    Loading.dismiss();
    update();
  }
}

class SePayOrderBean {
  String? goodsCode;
  String? goodsName;
  String? orderNo;
  double? payAmount;
  double? paidAmount;
  String? paidCurrency;

  SePayOrderBean({this.goodsCode, this.goodsName, this.orderNo, this.payAmount, this.paidAmount, this.paidCurrency});

  SePayOrderBean.fromJson(Map<String, dynamic> json) {
    if (json["goodsCode"] is String) {
      goodsCode = json["goodsCode"];
    }
    if (json["goodsName"] is String) {
      goodsName = json["goodsName"];
    }
    if (json["orderNo"] is String) {
      orderNo = json["orderNo"];
    }
    if (json["payAmount"] is num) {
      payAmount = (json["payAmount"] as num).toDouble();
    }
    if (json["paidAmount"] is num) {
      paidAmount = (json["paidAmount"] as num).toDouble();
    }
    if (json["paidCurrency"] is String) {
      paidCurrency = json["paidCurrency"];
    }
  }
}
